{% load querystring from django_tables2 %}
{% load get_item table_config_button from helpers %}

{% with last_column_name=table.columns.names|last %}
    <table{% if table.attrs %} {{ table.attrs.as_html }}{% endif %}>
        {% if table.show_header %}
            <thead>
                <tr>
                    {% for column in table.columns %}
                        {% if not table.configurable or not forloop.last or last_column_name != 'actions' %}
                            {% if column.orderable %}
                                <th {{ column.attrs.th.as_html }}><a href="{% querystring table.prefixed_order_by_field=column.order_by_alias.next %}" data-column-name="{{ column.name }}">{{ column.header }}</a></th>
                            {% else %}
                                <th {{ column.attrs.th.as_html }}>{{ column.header }}</th>
                            {% endif %}
                        {% else %}
                            <th {{ column.attrs.th.as_html }}>
                                {% table_config_button table %}
                            </th>
                        {% endif %}
                    {% endfor %}
                    {% if table.configurable and last_column_name != 'actions' %}
                        <th class="nb-actionable nb-w-0">
                            {% table_config_button table %}
                        </th>
                    {% endif %}
                </tr>
            </thead>
        {% endif %}
        <tbody>
            {% for row in table.page.object_list|default:table.rows %}
                <tr {{ row.attrs.as_html }}>
                    {% for column, cell in row.items %}
                        <td {{ column.attrs.td.as_html }}>{{ cell }}</td>
                    {% endfor %}
                    {% if table.configurable and last_column_name != "actions" %}
                        <td class="nb-w-0" />
                    {% endif %}
                </tr>
            {% empty %}
                {% if table.empty_text %}
                    <tr>
                        <td
                            colspan="{% if last_column_name == 'actions' %}{{ table.columns|length }}{% else %}{{ table.columns|length|add:1 }}{% endif %}"
                            class="text-center text-secondary"
                        >
                            &mdash; {{ table.empty_text }} &mdash;
                        </td>
                    </tr>
                {% endif %}
            {% endfor %}
        </tbody>
        {% if table.has_footer %}
            <tfoot>
                <tr>
                    {% for column in table.columns %}
                        <td>{{ column.footer }}</td>
                    {% endfor %}
                    {% if table.configurable and last_column_name != "actions" %}
                        <td class="nb-w-0" />
                    {% endif %}
                </tr>
            </tfoot>
        {% endif %}
    </table>
{% endwith %}
